<?php

namespace app\shop\model\coupon;

use app\shop\library\ShopAuth;
use app\shop\model\BaseModel;
use app\shop\model\user\UserCouponModel;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;

class CouponCenterModel extends BaseModel
{
    protected $name = 'shop_coupon_center';

    /**
     * 优惠券关联
     * @return BelongsTo
     */
    public function coupon(): BelongsTo
    {
        return $this->belongsTo(CouponModel::class, 'coupon_id', 'id')
            ->bind(['name', 'discount_type', 'discount_amount', 'discount_ratio', 'min_price', 'range_type']);
    }

    /**
     * 用户优惠券关联
     * @return HasMany
     */
    public function userCoupon(): HasMany
    {
        $user_id = ShopAuth::instance()->id;

        return $this->hasMany(UserCouponModel::class, 'coupon_center_id', 'id')
            ->where('user_id', $user_id);
    }

    /**
     * 修改器：优惠券可用范围
     * @param $value
     * @return string
     * @noinspection PhpUnused
     */
    public function setRangeGoodsIdsAttr($value): string
    {
        return implode(',', $value);
    }

    /**
     * 获取器：优惠券禁止状态
     * @param $value
     * @param $data
     * @return bool
     * @noinspection PhpUnused
     */
    public function getDisabledAttr($value, $data): bool
    {
        if ($this->getRanOutAttr($value, $data)) {
            return true;
        }
        if ($this->getEndedAttr($value, $data)) {
            return true;
        }

        return $this->getReceivedAttr($value, $data);
    }

    /**
     * 获取器：是否已抢完
     * @param $value
     * @param $data
     * @return bool
     * @noinspection PhpUnusedParameterInspection
     */
    public function getRanOutAttr($value, $data): bool
    {
        return $data['remain_num'] <= 0;
    }

    /**
     * 获取器：是否已领取
     * @param $value
     * @param $data
     * @return bool
     * @noinspection PhpUnusedParameterInspection
     */
    public function getReceivedAttr($value, $data): bool
    {
        return count($this->user_coupon) === $data['limit_num'];
    }

    /**
     * 获取器：领券活动是否已结束
     * @param $value
     * @param $data
     * @return bool
     * @noinspection PhpUnusedParameterInspection
     */
    public function getEndedAttr($value, $data): bool
    {
        return time() > $data['active_end_time'];
    }
}